/***************************************************************************\
 * The Mattise Kernel														*
 * Copyright 2007 Matthew Iselin											*
 * Licensed under the GPL													*
 *																			*
 * msgio.c																	*
 *																			*
 * Message I/O																*
 *																			*
\***************************************************************************/

// Includes
#include "mmsg.h"

// Functions

// Sends a message
int mattiseSendMessage( int destpid, int msgcode, char* msgbuff, int len )
{
	// send the message
	unsigned int ebx;
	__asm__ __volatile__ ( "int $0x80" : "=b" (ebx) : "a" (27), "b" (destpid), "c" (msgcode), "d" (len), "S" ((unsigned int) msgbuff) );
	return ebx;
}

// Allocates a buffer for a received message
char* mattiseAllocMessage()
{
	// allocate a buffer for the message
	unsigned int bsize;
	__asm__ __volatile__ ( "int $0x80" : "=b" (bsize) : "a" (30) );
	if( bsize == -1 || bsize == 0 )
		return ((char*) 0);
	unsigned int ebx;
	__asm__ __volatile__ ( "int $0x80" : "=b" (ebx) : "a" (35), "c" (bsize) );
	return ((char*) ebx);
}

// Allocates a buffer for a received message
char* mattiseAllocMessageSz( int sz )
{
	// allocate a buffer for the message
	unsigned int ebx;
	__asm__ __volatile__ ( "int $0x80" : "=b" (ebx) : "a" (35), "c" (sz) );
	return ((char*) ebx);
}

// Gets the size of the next message in the queue
int mattiseGetMessageSize()
{
	unsigned int bsize;
	__asm__ __volatile__ ( "int $0x80" : "=b" (bsize) : "a" (30) );
	return bsize;
}

// Frees a message buffer
void mattiseFreeMessage( char* tmp )
{
	// free the buffer
	if( tmp )
		__asm__ __volatile__ ( "int $0x80" : : "a" (37), "S" ((unsigned int) tmp) );
}

// Checks for a message
int mattiseHasMessage()
{
	// check for a message
	unsigned int ebx = 0;
	__asm__ __volatile__ ( "int $0x80" : "=b" (ebx) : "a" (29) );
	return ebx;
}

// Receives a message
char* mattiseRecvMessage( struct RecvMsgData* dat )
{	
	// get the message
	unsigned int ebx;
	__asm__ __volatile__ ( "int $0x80" : "=b" (ebx), "=c" (dat->msgcode), "=d" (dat->len) : "a" (28) );

	// return the pointer
	return ((char*) ebx);
}
